<template>
  <div class='page-content'>

    <!-- 工具栏区域 -->
    <table-bar :showTop="false"
               :columns="columns"
               @changeColumn="changeColumn">
      <!-- 条件查询区域 -->
      <div slot="top">
        <el-form label-width="70px">

          <el-row :gutter="20">
            <el-col :xs="24"
                    :sm="12"
                    :lg="8">
              <el-form-item label="关键词：">
                <el-input v-model="value"
                          placeholder="输入加工产品类型名或商家名称查询"></el-input>
              </el-form-item>
            </el-col>
            <el-row :xs="24"
                    :sm="12"
                    :lg="6"
                    style="float: right; margin-right: 10px;">
              <el-button type="primary"
                         @click="query">搜索</el-button>
              <el-button>重置</el-button>
            </el-row>
          </el-row>
        </el-form>
      </div>
      <!-- 左侧按钮 -->
      <div slot="bottom">
        <el-button type="primary"
                   plain
                   @click="showAddDialog">新增流程</el-button>
        <el-button type="danger"
                   plain
                   @click="delAll">批量删除</el-button>
      </div>

    </table-bar>

    <!-- 表格区域 -->
    <the-table :data="processList"
               :showPage="false"
               @getDataBySelectBox="handleSelectionChange"
               ref="flowListRef">
      <!-- 选择列 -->
      <el-table-column type="selection"
                       width="55"></el-table-column>

      <el-table-column label="序号"
                       type="index"
                       v-if="columns[0].show" />
      <el-table-column label="加工流程id"
                       prop="processId"
                       v-if="columns[1].show" />
      <el-table-column label="加工流程名称"
                       prop="processName"
                       v-if="columns[2].show" />
      <el-table-column label="加工流程描述"
                       prop="processDescribe"
                       v-if="columns[3].show" />
      <el-table-column label="修改时间"
                       prop="gmtModified"
                       v-if="columns[4].show" />
      <el-table-column label="创建时间"
                       prop="gmtCreate"
                       v-if="columns[5].show" />

      <el-table-column label="操作"
                       fixed="right"
                       width="200px"
                       v-if="columns[4].show">
        <template slot-scope="scope">
          <el-button type="text"
                     icon="el-icon-document"
                     @click="showDetailsDialog(scope.row)">
            详情
          </el-button>
          <el-button type="text"
                     icon="el-icon-edit"
                     @click="showEditDialog(scope.row)">
            编辑
          </el-button>
          <el-button type="text"
                     style="color: #FA6962"
                     icon="el-icon-delete"
                     @click="delById(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </the-table>

    <!-- 分页器区域 -->
    <el-pagination layout="total, sizes, prev, pager, next, jumper"
                   :page-sizes="[5, 8, 10, 15]"
                   :page-size="pageSize"
                   :current-page="pageNum"
                   :total="total"
                   @size-change="handleSizeChange"
                   @current-change="handleCurrentChange"
                   class="page">
    </el-pagination>

    <!-- 新增&修改流程对话框 -->
    <el-dialog :title="isShowAddForm?'新增流程':'修改流程'"
               :visible.sync="addDialog"
               width="50%">
      <el-form ref="addFormRef"
               :model="addForm"
               :rules="addFormRules"
               label-width="100px">

        <el-form-item label="流程名称"
                      prop="processName">
          <el-input v-model="addForm.processName"></el-input>
        </el-form-item>
        <el-form-item label="流程描述"
                      prop="processDescribe">
          <el-input v-model="addForm.processDescribe"></el-input>
        </el-form-item>
        <el-divider>关联工艺</el-divider>

        <el-steps :active="active"
                  finish-status="success"
                  align-center>
          <el-step title="工艺选取"></el-step>
          <el-step title="工艺排序"></el-step>
        </el-steps>
        <!-- 工艺列表 -->
        <the-table v-show="active === 0"
                   height="250"
                   :data="technologyList"
                   :showPage="false"
                   @getDataBySelectBox="handlesortListChange"
                   ref="table">
          <el-table-column type="selection"
                           width="55"></el-table-column>

          <el-table-column label="工艺名称"
                           prop="technologyName" />
          <el-table-column label="工艺描述"
                           :show-overflow-tooltip="true"
                           prop="technologyDescribe" />

        </the-table>
        <!-- 工艺排序 -->
        <sort-table v-show="active === 1"
                    :data="sortTechnologyList"
                    @change="handleSortTableChange"
                    height="250">
          <el-table-column label="工艺名称"
                           prop="echnologyName" />
          <el-table-column label="工艺描述"
                           prop="technologyDescribe" />
        </sort-table>

      </el-form> <span slot="footer"
            class="dialog-footer">
        <el-button :disabled="isSelect"
                   @click="next">{{active===0?'下一步':'上一步'}}
        </el-button>
        <el-button @click="addDialog = false">取 消</el-button>
        <el-button type="primary"
                   @click="()=>isShowAddForm?add():update()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 流程详情对话框 -->
    <el-dialog title="加工流水线1"
               :visible.sync="detailsDialog"
               width="50%">

      <div>
        <the-table :data="flowDetailsList"
                   :showPage="false">

          <el-table-column label="序号"
                           type="index" />

          <el-table-column label="加工工艺"
                           prop="technologyName" />
          <el-table-column label="加工工艺描述"
                           prop="technologyDescribe" />
          <el-table-column label="创建时间"
                           prop="gmtCreate" />

          <el-table-column label="修改时间"
                           prop="gmtModified" />

        </the-table>
      </div>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="detailsDialog = false">取 消</el-button>
        <el-button type="primary"
                   @click="detailsDialog = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>

import { changeColumn, pagination, dialogClose, multipleSelection, queryForm } from '@/api/mixin'
import { dateShorter } from '@/utils/utils'


export default {
  name: "ProcessManage_P",
  meta: {
    title: "加工流程",
  },
  mixins: [changeColumn, pagination, dialogClose, queryForm, multipleSelection,
  ],
  created () {
    this.getProcessList()
  },
  computed: {
    select_processingId () {
      return this.$store.state.Usersetting.ProcessInfo.processingId
    }
  },
  data () {
    return {
      columns: [
        { name: "序号", show: true },
        { name: "加工流程id", show: true },
        { name: "加工流程名称", show: true },
        { name: "加工流程描述", show: true },
        { name: "创建时间", show: true },
        { name: "修改时间", show: true },
        { name: "操作", show: true },
      ],
      processList: [],
      //新增流程对话框
      addDialog: false,
      editDialog: false,
      detailsDialog: false,
      flowDetailsList: [],
      // 条件查询参数
      value: '',
      // 新增流程表单
      addForm: {
        processDescribe: '',
        processName: '',
        processingId: '', //所属加工厂id
        processingFlowBindDtos: [
          {
            sortId: 0,
            technologyIds: 0
          }
        ]//关联工艺列表
      },
      addFormRules: {
        processName: [{ required: true, message: '请输入流程名称', trigger: 'blur' }, { min: 2, max: 15, message: '长度在 2 到 15 个字符', trigger: 'blur' }],
        processDescribe: [{ required: true, message: '请输入流程描述', trigger: 'blur' }, { min: 2, max: 15, message: '长度在 2 到 15 个字符', trigger: 'blur' }],
        processingId: [{ required: true, message: '请输入所属加工厂', trigger: 'blur' }]
      },
      technologyList: [],//可绑定得工艺列表
      editForm: {
        processingId: 0,//所属加工流程id
        processDescribe: '',
        processName: ''
      },
      processId: '',
      isShowAddForm: true,
      isSelect: true,
      active: 0,
      technologyList: [],
      sortTechnologyList: []
    }
  },
  methods: {
    //展示流程详情对话框
    async showDetailsDialog ({ processId }) {
      console.log('processId', processId);

      const { data: res } = await this.$http.get(`/processing/processing-flow/get/${processId}/${this.pageNum}/${this.pageSize}`)

      if (res.statusCode !== 20000) return this.$message.error('获取详情失败')

      dateShorter(res.data.records, 'gmtModified')
      dateShorter(res.data.records, 'gmtCreate')


      this.flowDetailsList = res.data.records

      this.detailsDialog = true
    },
    //分页器变化监听
    getList () {
      this.getProcessList()
    },
    // 分页
    async getProcessList () {
      const { data: res } = await this.$http.get(`/processing/processing-flow/page/${this.pageNum}/${this.pageSize}`, { params: { processingId: this.select_processingId } })
      if (res.statusCode !== 20000) return this.$message.error('获取流程列表失败')

      // console.log('getProcessList', res);
      dateShorter(res.data.records, 'gmtCreate')
      dateShorter(res.data.records, 'gmtModified')
      this.processList = res.data.records
      this.total = res.data.total
    },
    async query () {
      const { data: res } = await this.$http.get(`/processing/processing-flow/like/${this.value}/${this.pageNum}/${this.pageSize}`, { params: { processingId: this.select_processingId } })

      if (res.statusCode !== 20000) return this.$message.error('查询失败')


      dateShorter(res.data.records, 'gmtCreate')
      dateShorter(res.data.records, 'gmtModified')
      this.processList = res.data.records
      this.total = res.data.total
      this.$message.success('查询成功')

    },

    /* 编辑 */
    async showEditDialog ({ processId }) {
      //保存id
      this.processId = processId
      //获取最新的记录
      const { data: res } = await this.$http.get(`/processing/processing-flow/information/${processId}`)
      if (res.statusCode !== 20000) return this.$message.error('获取最新的流程记录失败')

      //保存
      this.addForm.processingId = res.data.processingId
      this.addForm.processName = res.data.processName
      this.addForm.processDescribe = res.data.processDescribe

      //获取工艺列表
      this.getTechnologyList()

      //处理获取的记录的工艺
      let stringTechnologyList = []
      if (res.data.processDescribe.length) {
        stringTechnologyList = res.data.processDescribe.split('->')
      }
      // console.log(stringTechnologyList);

      //在所有工艺中，标记流程记录原有的
      const rowTechnologyList = []
      stringTechnologyList.forEach(x => {
        const target = this.technologyList.find(item => item.echnologyName === x)
        rowTechnologyList.push(target)
      })

      this.toggleSelection(rowTechnologyList)


      // 显示
      this.isShowAddForm = false
      this.addDialog = true
    },
    update () {
      // 表单验证
      this.$refs.addFormRef.validate(async flag => {
        if (!flag)
          return this.$message.error('请正确填写表单')
        // 发送请求
        const { data: res } = await this.$http.put(`/processing/processing-flow/update/${this.processId}`, this.editForm)
        if (res.statusCode !== 20000) return this.$message.error('修改失败')


        // 关闭
        this.addDialog = false
        this.$message.success('修改成功')

        //刷选列表
        this.getProcessList()

      })





    },
    /* 编辑 */

    /* 删除 */
    delById ({ processId }) {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`/processing/processing-flow/deletion/${processId}`)

        if (res.statusCode !== 20000) return this.$message.error('删除失败')

        this.$message.success('删除成功')
        this.getProcessList()

      }).catch(() => {
        this.$message('已取消删除!')
      })
    },
    delAll () {
      if (this.multipleSelection.length === 0)
        return this.$message.error('未选中记录')

      this.$confirm('此操作将永久删除这些记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const ids = []

        this.multipleSelection.forEach(x => ids.push(x.processId))

        const { data: res } = await this.$http.delete(`/processing/processing-flow/deletion/batch`, {
          data: ids,
          headers: {
            'Content-Type': 'application/json'
          },
        })//参数置于请求体

        if (res.statusCode !== 20000) return this.$message.error('删除失败')

        this.$message.success('批量删除成功')
        this.getProcessList()

      })
        .catch(() => {
          this.$message('已取消删除!')
        })

    },
    /* 删除 */


    /* 新增 */
    async showAddDialog () {
      //通过vuex获取加工厂id
      this.addForm.processingId = this.select_processingId

      this.getTechnologyList()

      this.addDialog = true
    },
    async add () {
      this.addForm.processingFlowBindDtos = []
      //保存工序
      this.sortTechnologyList.forEach((item, index) => {
        this.addForm.processingFlowBindDtos.push({
          sortId: index,
          technologyIds: item.technologyId
        })
      })
      this.$refs.addFormRef.validate(async flag => {
        if (!flag)
          return this.$message.error('请正确填写表单')
        const { data: res } = await this.$http.post(`/processing/processing-flow/`, this.addForm)
        if (res.statusCode !== 20000) return this.$message.error('添加失败')

        this.$message.success('添加成功')
        this.getProcessList()
        this.addDialog = false
      })

    },
    // 工艺数据多选
    handlesortListChange (val) {
      if (val.length > 0) {
        this.sortTechnologyList = val
        this.isSelect = false
      }
      else {
        this.isSelect = true

      }
    },
    /* 排序 */
    handleSortTableChange (val) {
      // 保存排序后的数组
      this.sortTechnologyList = val

      val.map(item => console.log(item.technologyName))
    },
    next () {
      if (this.active === 0) {
        // 下一步
        this.active = 1
      } else {
        // 返回上一步
        this.active = 0
        // 禁用按钮,需要重选数据解开
        // this.isSelect = true

      }
    },
    dialogClose () {
      // 重置设置
      this.active = 0
      // this.technologyList = []
      this.sortTechnologyList = []
    },
    async getTechnologyList () {

      const { data: res } = await this.$http.get(`/processing/processing-technology/page/1/100`, { params: { processingId: this.select_processingId } })
      if (res.statusCode !== 20000) return this.$message.error('获取工艺列表失败')
      this.technologyList = res.data.records

    },
    //多选框勾选
    toggleSelection (rows) {
      /* console.log(this.$refs.mytable, ' this.$refs.mytable');
      if (rows) {
        rows.forEach(row => {
          this.$refs.mytable.toggleRowSelection(row);
        });
      } else {
        this.$refs.mytable.clearSelection();
      }
      console.log(11); */
    }

    /* 新增 */

  }
}
</script>

<style lang="scss" scoped>
.page {
  margin-top: 6px;
  text-align: center;
}
</style>
